// 回调函数快速转换promise对象
export function promisify(func: Function, _this?: any): Function {
  return (...args: any[]) =>
    new Promise((resolve, reject) => {
      func.apply(_this, [
        ...args,
        (err: any, data: any) => {
          return err ? reject(err) : resolve(data);
        },
      ]);
    });
}

// 等待函数(毫秒)
export function delay(time: number): Promise<number> {
  return new Promise((resolve) => setTimeout(resolve, time));
}

// 防抖函数(固定时间延迟间隔只触发一次)， 监听页面滚动、实时搜索框,
export function debounce(func: Function, wait = 1000): Function {
  let timer: any;
  return function () {
    const context = this;
    const args = arguments;
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}

// 节流函数(固定时间内只触发一次)，按钮点击防止重复提交, leading节流开始前执行
export function throttle(
  func: Function,
  wait = 1000,
  leading = true
): Function {
  let timer: any;
  return function () {
    const context = this;
    const args = arguments;
    if (!timer) {
      timer = setTimeout(() => {
        if (!leading) func.apply(context, args);
        timer = null;
      }, wait);
      if (leading) func.apply(context, args);
    }
  };
}

// 节流函数带参数(固定时间内只触发一次，并合并请求参数，追加在末尾), 固定节流结束后执行
export function throttleWithArgsList(func: Function, wait = 1000): Function {
  let timer: any;
  let argsList: any[] = [];
  return (...args: []) => {
    if (!timer) {
      timer = setTimeout(() => {
        func.apply(this, [...args, argsList]);
        argsList = [];
        timer = null;
      }, wait);
    }
    argsList.push(args);
  };
}
